import { Router } from 'express'
import { auth, role } from '../middleware/auth.js'
import { Leave } from '../models/Leave.js'
import { loadLeave } from '../middleware/permission.js'

const router = Router()
router.use(auth, role('admin'))

router.get('/leaves', async (req, res, next) => {
  try {
    const {
      status,
      type,
      page = 1,
      pageSize = 10,
      sortBy = 'created_at',
      sortOrder = 'desc',
    } = req.query

    const result = await Leave.findAll({
      status,
      type,
      page: Number(page),
      limit: Math.min(100, Number(pageSize)),
      sortBy,
      order: sortOrder,
    })

    res.json({
      code: 0,
      message: 'ok',
      data: {
        total: result.total,
        page: result.page,
        pageSize: result.limit,
        rows: result.list,
      },
    })
  } catch (error) {
    next(error)
  }
})

router.get('/leaves/:id', loadLeave, async (req, res, next) => {
  try {
    res.json({ code: 0, message: 'ok', data: req.leave })
  } catch (error) {
    next(error)
  }
})

router.post('/leaves/:id/cancel', loadLeave, async (req, res, next) => {
  try {
    const id = Number(req.params.id)
    const success = await Leave.updateStatus(id, 'cancelled')
    if (!success) return res.status(404).json({ code: 404, message: '未找到' })
    const it = await Leave.findByIdWithSteps(id)
    res.json({ code: 0, message: 'ok', data: it })
  } catch (error) {
    next(error)
  }
})

router.post('/leaves/:id/mark-invalid', loadLeave, async (req, res, next) => {
  try {
    const id = Number(req.params.id)
    const success = await Leave.updateStatus(id, 'invalid')
    if (!success) return res.status(404).json({ code: 404, message: '未找到' })
    const it = await Leave.findByIdWithSteps(id)
    res.json({ code: 0, message: 'ok', data: it })
  } catch (error) {
    next(error)
  }
})

router.get('/stats', async (req, res, next) => {
  try {
    const stats = await Leave.getStats()

    const total = parseInt(stats.total) || 0
    const approved = parseInt(stats.approved) || 0
    const rejected = parseInt(stats.rejected) || 0
    const pending = parseInt(stats.pending) || 0
    const passRate = total ? Math.round((approved / (approved + rejected || 1)) * 100) : 0
    const avgHours = stats.totalHours && total ? (stats.totalHours / total).toFixed(1) : '0.0'

    res.json({
      code: 0,
      message: 'ok',
      data: { total, approved, rejected, pending, passRate, avgHours },
    })
  } catch (error) {
    next(error)
  }
})

export default router
